'use strict'

define(['jquery' , 'bootstrap', 'bootstrapTable', 'bootstrapTableCN' , 'select2' , 'switch' , 'validate' , 'validate.en' , 'shiftform' , 'uploader' , 'plupload' , 'qiniu'], function($) {
  return {
    init : function(data){
      this.initPage(data.principalId);
      this.editPrincipal();
      this.editPrincipalProfile();
      this.editPrincipalAvatar();
      this.editSettlement();
      this.editAppointDays();
    },
    
    initPage: function(principalId) {
    	$('#grid-wrap').on("click", ".pagination a", function(event){
            event.preventDefault();
            $.ajax({
              url: $(this).attr("href"),
              type : "GET"
            }).done(function( data ) {
          	  $("#grid-wrap").empty().append(data);
            });
          })

          // init grid wrap
          $.ajax({
            url: window.__CTX__.root + '/principals/' + principalId + '/grid',
            type: "GET"
          }).done(function( data ) {
          	$("#grid-wrap").empty().append(data);
          });
    },
    
    editPrincipal : function(){
    
      $(document).on("shown.bs.modal" , "#edit-principal" , function(e){
      
      $(e.currentTarget).find('form[data-validate="true"]').bt_validate();  //bind validate
      
        var $form = $(e.currentTarget).find("form")                          //bind shiftform
        $form.shiftform({
          beforeSubmit : function(el) {
            $form.trigger("validate.ajax.submit");
            return $.bt_validate.result[$.bt_validate.form_id]
          }
        })
        
      });
      
    },
    
    editPrincipalProfile : function(){
    
      $(document).on("shown.bs.modal" , "#principal-profile-edit" , function(e){
      
      $(e.currentTarget).find('form[data-validate="true"]').bt_validate();  //bind validate
      
      var $form = $(e.currentTarget).find("form")                          //bind shiftform
        $form.shiftform({
          beforeSubmit : function(el) {
            $form.trigger("validate.ajax.submit");
            return $.bt_validate.result[$.bt_validate.form_id]
          }
        })
        
      });
      
    },
    
    editPrincipalAvatar : function(){
      var that = this;
      $(document).on("shown.bs.modal" , "#principal-avatar-edit" , function(e){
        $(e.currentTarget).find('form[data-validate="true"]').bt_validate();  //bind validate
        
        that.initUpload();
        
        var $form = $(e.currentTarget).find("form")                          //bind shiftform
        $form.shiftform({
          beforeSubmit : function(el) {
            $form.trigger("validate.ajax.submit");
            return $.bt_validate.result[$.bt_validate.form_id]
          }
        })
        
      });
      
    },
    
    editSettlement : function(){
        
        $(document).on("shown.bs.modal" , "#edit-settlement" , function(e){
        
          $(e.currentTarget).find('form[data-validate="true"]').bt_validate();  //bind validate
        
          var $form = $(e.currentTarget).find("form")                          //bind shiftform
          $form.shiftform({
            beforeSubmit : function(el) {
              $form.trigger("validate.ajax.submit");
              return $.bt_validate.result[$.bt_validate.form_id]
            }
          })
          
        });
        
    },
    
    initUpload: function() {
        
      var imgSrc = $(".upload-cover").find("img").attr("src");
      if(imgSrc == null || imgSrc == undefined) {
        $(".upload-cover").find("img").addClass("hide");
      }
      
      $(".upload-cover").hover(function(){
        $(".upload-cover .edit-btn").addClass("in");
      },function(){
        $(".upload-cover .edit-btn").removeClass("in");
      });
      
      $.ajax({
      
        url: window.__CTX__.cloudUptoken,
        // The name of the callback parameter, as specified by the YQL service
        jsonp: "callback",
        // Tell jQuery we're expecting JSONP
        dataType: "jsonp",
        // Work with the response
        success: function( response ) {
          var uploaderCover = Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: 'pickCover',
            uptoken: response.token,
            domain: 'http://upload.qiniu.com/',
            max_file_size: '4mb',
            max_retries: 3,
            chunk_size: '2mb',
            save_key: true,
            auto_start: true,
            init: {
              'UploadProgress': function(up, file) {
                $('#messageCover').removeClass("hide");
                $(".edit-btn").addClass("hide").prop("disabled", true);
                $('#messageCover').html("正在上传图片，请稍后");
                $('#submitBtn').attr("disabled", "disabled");
              },
              'FileUploaded': function(up, file, info) {
                var res = $.parseJSON(info);
                var cover_box = '';
                $('#coverPreview').attr("src", window.__CTX__.cloudProd + "/" + res.key + "-0.6");
                $('#coverPreviewList').css("display", "block");
                $('#cover').val(res.key);
                $('#messageCover').html("加载图片完成");
                setTimeout(function() {
                  $('#messageCover').addClass("hide");
                  $(".edit-btn").addClass("fade").removeClass("hide").prop("disabled", false).html("<span class='glyphicon glyphicon-repeat' aria-hidden='true'></span>&nbsp;&nbsp;重新上传");
                }, 2000);
                $('#submitBtn').removeAttr('disabled');
              },
              'Error': function(up, err, errTip) {
                $('#messageCover').html("图片上传异常，请稍后重试");
              }
            }
          });
        }
      });
    },
   
    editAppointDays: function() {
        $(document).on("shown.bs.modal" , "#edit-appoint-days" , function(e){
            $('select[name="appointOption"]').select2({
                placeholder : '请选择可预约日期',
                minimumResultsForSearch : -1,
                allowClear : false
            });
            
            $('select[name="appointDays"]').select2({
                placeholder : '请指定日期',
                minimumResultsForSearch : -1,
                allowClear : true
            });
            
            $('select[name="appointOption"]').on('change', function() {
                var appointOption = $(this).val();
                
                if(appointOption == 'appoint') {
                    var orginalAppointDays = $('input[name="orginalAppointDays"]').val();
                    
                    $(".appointOption").after('<div class="form-group appoint">'
                                              + '<label class="control-label col-xs-4">指定日期：</label>'
                                              + '<div class="col-xs-6 pull-left">'
                                                + '<select name="appointDays" multiple class="form-control" data-validate="required">'
                                                  + '<option></option>'
                                                  + '<option value="1"' + (orginalAppointDays.indexOf('1,')!=-1 ? ' selected' : '') + '>周一</option>'
                                                  + '<option value="2"' + (orginalAppointDays.indexOf('2,')!=-1 ? ' selected' : '') + '>周二</option>'
                                                  + '<option value="3"' + (orginalAppointDays.indexOf('3,')!=-1 ? ' selected' : '') + '>周三</option>'
                                                  + '<option value="4"' + (orginalAppointDays.indexOf('4,')!=-1 ? ' selected' : '') + '>周四</option>'
                                                  + '<option value="5"' + (orginalAppointDays.indexOf('5,')!=-1 ? ' selected' : '') + '>周五</option>'
                                                  + '<option value="6"' + (orginalAppointDays.indexOf('6,')!=-1 ? ' selected' : '') + '>周六</option>'
                                                  + '<option value="7"' + (orginalAppointDays.indexOf('7,')!=-1 ? ' selected' : '') + '>周日</option>'
                                                + '</select>'
                                              + '</div>'
                                            + '</div>');
                    
                    $('select[name="appointDays"]').select2({
                        placeholder : '请指定日期',
                        minimumResultsForSearch : -1,
                        allowClear : true
                    });
                    
                    $(e.currentTarget).find('form[data-validate="true"]').bt_validate();
                } else {
                    $(".appoint").remove();
                }
            });
            
            $(e.currentTarget).find('form[data-validate="true"]').bt_validate();  //bind validate
            
            var $form = $(e.currentTarget).find("form")                          //bind shiftform
            $form.shiftform({
                beforeSubmit : function(el) {
                  $form.trigger("validate.ajax.submit");
                  return $.bt_validate.result[$.bt_validate.form_id]
                }
            });
        });
    }
  }
})